package net.chrisrichardson.ec2deployer.core

import org.apache.commons.logging.*

class ProcessExecutor {
    Log logger = LogFactory.getLog(getClass())

    public int execute(String cmd, String input = null, ProcessMonitor processMonitor = null) {
        logger.debug("Executing: " + cmd)
        Process p = cmd.execute()
        def dpm = processMonitor 
        if (dpm) {
            dpm.monitorProcess(p)
        } else {
            Thread.startDaemon {System.out << p.in}
            Thread.startDaemon {System.err << p.err}
        }
        if (input) {
            logger.debug "Sending input: $input"
            p.out << input
            p.out.close()
        }
        if (dpm == null || dpm.isWaitForOrKillRequired()) {
          logger.debug "waiting..."
          p.waitForOrKill(20 * 60 * 1000)
          logger.debug "done waiting: ${p.exitValue()}"
          dpm?.noteEndedOrTimedOut(p)
          return p.exitValue()
        } else {
            return 0
        }
    }

    public executeAsync(String cmd) {
        logger.debug("Executing: " + cmd)
        Process p = cmd.execute()
        if (processMonitor) {
            processMonitor.monitorProcess(p)
        } else {
            def dpm = defaultProcessMonitorHolder.get()
            if (dpm) {
                dpm.monitorProcess(p)
            } else {
                Thread.startDaemon {System.out << p.in}
                Thread.startDaemon {System.err << p.err}
            }
            if (input) {
                logger.debug "Sending input: $input"
                p.out << input
                p.out.close()
            }
            logger.debug "waiting..."
            p.waitForOrKill(20 * 60 * 1000)
            logger.debug "done waiting: ${p.exitValue()}"
            dpm?.noteEndedOrTimedOut(p)
        }
    }

}